<?php
class User extends Eloquent
{
    public static $timestamps = false;

    public static $key = 'userid';

    public static $rules = array( 
                                'username' => 'required|unique:users', 
                                'password' => 'required', 
                                'role' => ''
                            );

    
    public static function validate($data){
        return Validator::make($data, Static::$rules);
    }

    public function userprofile()
    {
        return $this->has_one('UserProfile','userid');
    }

    public function roles()
    {
        return $this->has_many_and_belongs_to('UserRole');
    }
    
    public static function listUser(){

        $allUser = User::all();

        $datagrid = new Datagrid;
        $datagrid->setFields(array('userprofile_fullname' =>'Fullname'));
        $datagrid->setFields(array('userprofile_emel' =>'Email'));
        $datagrid->setFields(array('userprofile_dob' =>'Date of Birth'));
        $datagrid->setAction('edit','editUser');
        $datagrid->setAction('delete','deleteUser');
        $datagrid->setTable('users','creep');
        $datagrid->build($allUser,'userid');

        return $datagrid->render();

    }



    public static function registerUser($input){

        $User = new User;
        $id = $User->insert_get_id(array('username' => $input['username'],'password'=> Hash::make($input['password']) , 'role'=>3));

        unset($input['username']);
        unset($input['password']);

        if($id){

        $extension = File::extension($input['imgpath']['name']);
        $directory = path('public').'avatar/'.sha1($id);
        $filename = sha1($id.time()).".{$extension}";

        if($input['imgpath']['size'] != null){

            $upload_success = Input::upload('photo', $directory, $filename);

            if( $upload_success ) {
                $input['imgpath'] = 'avatar/'.sha1($id).'/'.$filename;
            }else{
                $input['imgpath'] = '';
            }
        }else{
            $input['imgpath'] = '';
        }

            $profile = new UserProfile(array(
                'fullname' => $input['fullname'],
                'imgpath' => $input['imgpath'],
                'dob' => date('Y-m-d',strtotime($input['dob'])),
                'address' => $input['address'],
                'emel' => $input['emel'],
                'postcode' => $input['postcode']
            ));

            $user = User::find($id);
            $user->userprofile()->insert($profile);  

            return $profile->exists; 

        }else{
            return false;
        }   

        
    }
}